package com.fly.handler;

import com.fly.domain.Role;
import com.fly.domain.User;
import com.fly.service.RoleService;
import com.fly.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author Fly
 * @Description
 * @Date Created in 14:41 2018/1/29
 * @Modified by
 */
@Component
public class RoleHandler {

    private final RoleService roleService;

    @Autowired
    public RoleHandler(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 保存
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> save(ServerRequest serverRequest){
        Mono<Role> roleMono = serverRequest.bodyToMono(Role.class);
        Role role = roleMono.block();
        roleService.save(role);
        Response response = new Response(true,"保存成功",null);
        return ServerResponse.ok().body(fromObject(response));
    }
    /**
     * 查询列表
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> list(ServerRequest serverRequest){
        Flux<Role> roleFlux = Flux.fromIterable(roleService.findAll());
        return ServerResponse.ok().body(roleFlux,Role.class);
    }

    /**
     * 删除角色
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> remove(ServerRequest serverRequest){
        Long id = Long.valueOf(serverRequest.pathVariable("id"));
        roleService.removeRole(id);
        Response response = new Response(true,"删除成功",null);
        return ServerResponse.ok().body(fromObject(response));
    }
}
